package com.demo.gulimall.auth.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.demo.gulimall.auth.entity.Member;
import com.demo.gulimall.auth.entity.MemberLevel;
import com.demo.gulimall.auth.exception.OptionException;
import com.demo.gulimall.auth.mapper.MemberLevelMapper;
import com.demo.gulimall.auth.mapper.MemberMapper;
import com.demo.gulimall.auth.service.MemberService;
import com.demo.gulimall.auth.vo.MemberRegVo;
import com.demo.gulimall.common.utils.R;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.stereotype.Service;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;

/**
 * 会员
 *
 * @author Chen Yuan
 */

@Service
public class MemberServiceImpl extends ServiceImpl<MemberMapper, Member> implements MemberService {

    @Autowired
    private MemberMapper memberMapper;

    @Autowired
    private MemberLevelMapper memberLevelMapper;

    @Override
    public R memberReg(MemberRegVo memberReg) throws OptionException {
        Member member = new Member();

        // 默认登记
        MemberLevel memberLevel = memberLevelMapper.getDefaultMemberLevel();
        member.setLevelId(memberLevel.getId());

        // 检查用户名、手机号唯一性
        this.checkMemberPhoneUnique(memberReg.getPhone());
        this.checkMemberUserNameUnique(memberReg.getUsername());
        member.setMobile(memberReg.getPhone());
        member.setUsername(memberReg.getUsername());
        member.setNickname(memberReg.getUsername());

        // 对密码加密
        BCryptPasswordEncoder passwordEncoder = new BCryptPasswordEncoder();
        String encodePas = passwordEncoder.encode(memberReg.getPassword());
        member.setPassword(encodePas);

        baseMapper.insert(member);
        return R.ok();
    }


    @Override
    public void checkMemberUserNameUnique(String userName) throws OptionException {
        Integer rows = baseMapper.selectCount(new QueryWrapper<Member>().eq("username", userName));
        if (rows > 0) {
            throw new OptionException("用户名已存在");
        }
    }

    @Override
    public void checkMemberPhoneUnique(String phone) throws OptionException {
        Integer rows = baseMapper.selectCount(new QueryWrapper<Member>().eq("mobile", phone));
        if (rows > 0) {
            throw new OptionException("手机号已存在");
        }
    }
}
